import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useAuth } from '@/composables/useAuth.ts'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeLayout.vue'),
      children: [
        {
          path: '',
          name: 'ChatHome',
          component: () => import('../views/chat/ChatHome.vue')
        },
        {
          path: '/chat/:chatId',
          name: 'ChatIndex',
          component: () => import('../views/chat/ChatIndex.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/auth/LoginIndex.vue'),
    },
    {
      path: '/error',
      name: 'error',
      children: [
        {
          path: '404',
          name: 'notFound',
          component: () => import('@/views/error/404.vue'),
        },
      ],
    },
    {
      path: '/:path(.*)*',
      redirect: '/error/404', // 路径未找到，则重定向到404页面
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('@/views/test/Test.vue'),
    },
    {
      path: '/demo',
      name: 'demo',
      component: () => import('@/views/test/Demo.vue'),
    },
    {
      path: '/redirect-to-analysis', // 内部路由路径
      name: 'redirectToAnalysis',
      component: () => import('@/views/empty/Empty.vue'), // 空组件（无需实际内容）
      meta: {
        externalLink: 'http://localhost:3000/' // 存储外部链接
      }
    }
  ],
})

router.beforeEach(async (to, from, next) => {
  const publicPages = ['/login', '/test','/error/404', '/redirect-to-analysis'] // 新增内部路由到公开页面
  const {isLogin} = useAuth()

  // 核心逻辑：拦截内部重定向路由，跳转到外部链接
  if (to.meta.externalLink) {
    // 打开外部链接（_blank 新标签页，可改为 _self 当前页）
    window.open(to.meta.externalLink as string, '_blank');
    // 跳转后返回原页面（或重定向到首页，避免停留在空组件）
    next(from.path);
    return; // 终止后续路由逻辑
  }

  // 原有鉴权逻辑保持不变
  if (!publicPages.includes(to.path) && !isLogin) {
    return next('/login')
  }

  next()
})

export default router
